package de.lmu.ifi.pst.uwejsf.framework.process;

import java.util.Map;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleScriptContext;

public class OGNLActivityGuardHandler extends BasicActivityGuardHandler {

	protected ScriptEngine scriptEngine;

	public OGNLActivityGuardHandler() {
		ScriptEngineManager manager = new ScriptEngineManager();
		scriptEngine = manager.getEngineByName("ognl");
	}

	@Override
	public GuardEvaluationResult evaluateGuardExpression(String expression,
			Map<String, Object> scope) {
		GuardEvaluationResult result = super.evaluateGuardExpression(
				expression, scope);
		if (result != GuardEvaluationResult.NOT_HANDLED)
			return result;
		ScriptContext context = new SimpleScriptContext();
		Bindings scriptScope = context.getBindings(ScriptContext.ENGINE_SCOPE);
		scriptScope.putAll(scope);
		Boolean evaluationResult = null;
		try {
			evaluationResult = (Boolean) scriptEngine.eval(expression,
					scriptScope);
		} catch (ScriptException e) {
			throw new ProcessDataflowException(
					"Couldn't evaluate guard expression: " + expression + ".",
					e);
		}
		if (evaluationResult)
			return GuardEvaluationResult.TRUE;
		else
			return GuardEvaluationResult.FALSE;

	}
}
